package com.cpi.cornpp.salesforcast.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.cpi.cornpp.common.exception.CornPPException;
import com.cpi.cornpp.salesforcast.converter.SalesForecastConverter;
import com.cpi.cornpp.salesforcast.dao.SalesForecastDAO;
import com.cpi.cornpp.salesforcast.exception.SalesForecastException;
import com.cpi.cornpp.salesforcast.view.SalesForecastView;

/**
 * Sales Forecast Service
 * @author Edgar Joao
 *
 */
public class SalesForecastService {
	/**
	 * Get Sales Forecast List
	 * @param searchView
	 * @return
	 * @throws SalesForecastException
	 */
	public List getSalesForecastList(SalesForecastView searchView) throws SalesForecastException{
		List salesForecastList = null;
		SalesForecastDAO dao = null;
		SalesForecastConverter converter = null;
		try{
			salesForecastList = new ArrayList(0);
			dao = new SalesForecastDAO();		
			converter = new SalesForecastConverter();
			salesForecastList.addAll(converter.convertDTOsToViews(dao.getSalesForecast(converter.convertSalesForecastViewToDTO(searchView))));
		} catch (SalesForecastException salesForecastException) {
			throw salesForecastException;
		} catch (Exception e){
			SalesForecastException salesForecastException = null;
			e.printStackTrace(System.out);
			salesForecastException = new SalesForecastException(e , CornPPException.LAYER_SERVICE,CornPPException.ACTION_INSERT);
			throw salesForecastException;
		}		
		return salesForecastList;
	}
	/**
	 * Insert Sales Forecast 
	 * @param view
	 * @throws SalesForecastException
	 */
	public void save(List salesForecastViews) throws SalesForecastException{
		SalesForecastDAO dao = null;		
		SalesForecastView view = null;		
		SalesForecastConverter converter = null;
		Iterator iterator = null;
		try{
			dao = new SalesForecastDAO();
			converter = new SalesForecastConverter();
			iterator = salesForecastViews.iterator();
			while(iterator.hasNext()){
				view = (SalesForecastView) iterator.next();			
				if(dao.existSalesForecast(converter.convertSalesForecastViewToDTO(view))){
					dao.updateSalesForecast(converter.convertSalesForecastViewToDTO(view));
				}else{
					dao.insertSalesForecast(converter.convertSalesForecastViewToDTO(view));					
				}
			}										
		} catch (SalesForecastException salesForecastException) {
			throw salesForecastException;
		} catch (Exception e){
			SalesForecastException salesForecastException = null;
			e.printStackTrace(System.out);
			salesForecastException = new SalesForecastException(e , CornPPException.LAYER_SERVICE,CornPPException.ACTION_INSERT);
			throw salesForecastException;
		}		
	}
}
